<template>
  <div>
    <a-modal
      v-model="visible"
      :title="modal_title"
      on-ok="handleOk"
      :after-close="clearMessage"
    >
      <template slot="footer">
        <a-button key="back" @click="handleCancel"> 返回 </a-button>
        <a-button
          key="submit"
          type="primary"
          :loading="loading"
          @click="handleOk"
        >
          提交
        </a-button>
      </template>
      <a-form :form="form" :label-col="{ span: 5 }" :wrapper-col="{ span: 12 }">
        <a-form-item label="用户名">
          <a-input
            v-decorator="[
              'username',
              {
                rules: [
                  { required: true, message: '请输入用户名' },
                  {
                    min: 0,
                    max: 8,
                    message: '长度需在0-8位之间',
                    trigger: 'blur',
                  },
                ],
              },
            ]"
            placeholder="请输入用户名"
          />
        </a-form-item>
        <a-form-item label="姓名">
          <a-input
            v-decorator="[
              'name',
              {
                rules: [
                  { required: true, message: '请输入姓名' },
                  {
                    min: 1,
                    max: 8,
                    message: '长度需在1-8位之间',
                    trigger: 'blur',
                  },
                ],
              },
            ]"
            placeholder="请输入姓名"
          />
        </a-form-item>
        <a-form-item label="头像">
          <div class="upLoadImg_class" v-if="avaUrl">
            <!-- <img :src="avaUrl" alt="" style="width: 50px; height: 50px" /> -->
            <a-avatar
              :size="30"
              :src="avaUrl"
              style="width: 50px; height: 50px"
            />
          </div>
          <div :key="ImgKey">
            <a-upload
              v-decorator="[
                'avatarUrl',
                {
                  initialValue: '',
                },
              ]"
              name="file"
              :multiple="true"
              :headers="pic_token"
              action="http://1.117.91.88:52016/fraud-prevention/api/admin/image"
              @change="handleChange"
              :remove="removeAvatar"
              placeholder="请上传头像"
            >
              <a-button v-if="state_update">
                <a-icon type="upload" /> 更换头像信息</a-button
              >
              <a-button v-else> <a-icon type="upload" /> 添加头像信息</a-button>
            </a-upload>
          </div>
        </a-form-item>
        <a-form-item label="性别">
          <a-select
            v-decorator="[
              'sex',
              {
                rules: [{ required: true, message: '请输入性别' }],
              },
            ]"
            placeholder="请选择性别"
          >
            <a-select-option value="0"> 男 </a-select-option>
            <a-select-option value="1"> 女 </a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item label="电话">
          <a-input
            v-decorator="[
              'tel',
              {
                rules: [
                  { required: true, message: '请输入电话' },
                  {
                    min: 6,
                    max: 11,
                    message: '长度需在6-11位之间',
                    trigger: 'blur',
                  },
                ],
              },
            ]"
            placeholder="请输入电话"
          />
        </a-form-item>
        <a-form-item label="邮箱">
          <a-input
            v-decorator="[
              'email',
              {
                rules: [
                  { required: true, message: '请输入邮箱' },
                  {
                    max: 27,
                    min: 10,
                    message: '邮箱格式不正确',
                    trigger: 'blur',
                  },
                ],
              },
            ]"
            placeholder="请输入邮箱"
          />
        </a-form-item>
        <a-form-item label="角色">
          <a-select
            mode="tags"
            v-decorator="[
              'roles',
              {
                rules: [{ required: true, message: '请分配用户角色' }],
              },
            ]"
            placeholder="请分配用户角色"
            ><a-select-option
              :value="item.id"
              v-for="item in role_list"
              :key="item.id"
              @change="handleRoleChange"
            >
              {{ item.name }}
            </a-select-option>
          </a-select>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>
<script>
export default {
  data() {
    return {
      formLayout: "horizontal",
      form: this.$form.createForm(this, { name: "coordinated" }),
      // 动态显示弹框标题
      modal_title: "",
      loading: false,
      // 存放发送请求的token
      pic_token: {},
      visible: false,
      role_list: [],
      // 存储上传图片的url
      avaUrl: "",
      // 判断是否是新增
      state_update: false,
      // 点击的ID
      Id: 0,
      fileList: [],
      ImgKey: "",
    };
  },
  created() {
    this.pic_token.authorization = window.localStorage.getItem("authorization");
  },
  //   /admin/actions
  methods: {
    clearMessage() {
      if (this.avaUrl != "") {
        this.handleCancel();
      }
    },
    // 在模态加载完成后 对select 进行选择上的填充
    init(state) {
      //如果是修改操作
      if (state) {
        this.$nextTick(async () => {
          this.modal_title = "更新";
          this.visible = true;
          // 设置更新标志 让确认时 发送不同的请求
          this.state_update = true;
          const { data: res } = await this.$http.get("/admin/role/all");
          console.log(res);
          if (res.code == 200) {
            this.role_list = res.data;
          }
        });
        this.$emit("refreshDataList");
      } else {
        this.visible = true;
        this.modal_title = "新增";
        this.state_update = false;
        this.avaUrl = "";
        // 新增操作
        this.$nextTick(async () => {
          this.form.resetFields();
          const { data: res } = await this.$http.get("/admin/role/all");
          console.log(res);
          if (res.code == 200) {
            this.role_list = res.data;
          }
        });
        this.$emit("refreshDataList");
      }
    },
    // 模态的确认按钮触发
    async handleOk(e) {
      e.preventDefault();
      this.form.validateFields(async (err, values) => {
        // 如果表单验证通过的话
        if (!err) {
          this.loading = true;
          if (this.state_update == false) {
            //新增操作
            const { data: res } = await this.$http.post("/admin/user", {
              username: values.username,
              name: values.name,
              avatarUrl: this.avaUrl,
              sex: Number(values.sex),
              tel: values.tel,
              email: values.email,
              roles: values.roles,
            });
            if (res.code == 200) {
              this.common.notify("success", "新增成功");
              this.$emit("refreshDataList");
              setTimeout(() => {
                this.visible = false;
                this.loading = false;
              }, 1000);
            } else {
              this.common.notify("warning", "填写格式不正确");

              setTimeout(() => {
                this.loading = false;
              }, 1000);
            }
          } else {
            //更新操作
            this.state_update == false; // 初始化
            const { data: res } = await this.$http.put("/admin/user", {
              id: this.Id,
              name: values.name,
              avatarUrl: this.avaUrl,
              sex: Number(values.sex),
              tel: values.tel,
              email: values.email,
            });
            if (res.code == 200) {
              this.common.notify("success", "修改成功");
              this.$emit("refreshDataList");
              setTimeout(() => {
                this.visible = false;
                this.loading = false;
              }, 1000);
            } else {
              this.common.notify("warning", "修改失败,请重试");

              // this.$message.warning("修改失败,请重试");
              setTimeout(() => {
                this.loading = false;
              }, 1000);
            }
          }
        }
      });
    },

    async handleCancel(e) {
      console.log("file", this.fileList);
      const { data: res } = await this.$http.delete(
        `/admin/image?url=${this.avaUrl}`
      );
      if (res.code == 200) {
        this.common.notify("success", "取消上传");
        this.visible = false;
        this.avaUrl = "";
      }
      this.visible = false;
      this.$emit("refreshDataList");
    },
    // 数组去重
    unique(arr) {
      return Array.from(new Set(arr));
    },
    update(record) {
      this.$nextTick(async () => {
        // 将ID放置全局 让其他人访问。
        // 将状态放置全局, 作用是 动态的显示与隐藏 图片上传Or 图片查看
        this.state_update = true;
        this.Id = record.id;

        this.init(this.state_update);
        // 将信息 填充到对应控件当中
        const { data: res } = await this.$http.get(`/admin/user/${record.id}`);

        this.avaUrl = res.data.avatarUrl;
        this.form.setFieldsValue({
          username: `${res.data.username}`,
          name: `${res.data.name}`,
          sex: `${res.data.sex}`,
          tel: `${res.data.tel}`,
          email: `${res.data.email}`,
          roles: `${res.data.roles}`,
        });
      });
    },
    handleChange(info) {
      let fileList = [...info.fileList];
      console.log("file", fileList);
      fileList = fileList.slice(-2);
      fileList = fileList.map((file) => {
        console.log("response", file.response.data);
        this.avaUrl = file.response.data; //如果有就传 没有就放空
        if (file.response) {
          file.url = file.response.url;
        }
        return file;
      });
    },
    async removeAvatar() {
      const { data: res } = await this.$http.delete(
        `/admin/image?url=${this.avaUrl}`
      );
      if (res.code == 200) {
        // this.common.notify("success", "已取消上传");
        this.avaUrl = "";
      }
    },
    handleRoleChange(value) {},
  },
  watch: {
    visible() {
      if (this.visible) {
        this.ImgKey = "";
      } else {
        this.ImgKey = Math.random();
      }
    },
  },
};
</script>
<style  lang='less' scoped>
.name_part {
  display: flex;
  .name_label {
    width: 50px;
    display: flex;
    justify-content: center;
    align-items: center;
    margin-left: 5px;
    margin-right: 28px;
  }
}
.desc_part {
  display: flex;
  margin-top: 20px;

  .desc_label {
    width: 50px;
    display: flex;
    justify-content: center;
    align-items: center;
    margin-left: 5px;
    margin-right: 30px;
  }
}
.permission_part {
  display: flex;
  margin-top: 20px;
  .permission_label {
    width: 50px;

    display: flex;
    justify-content: center;
    align-items: center;
    margin-left: 5px;
    margin-right: 25px;
  }
}
// /deep/ .ant-input-affix-wrapper .ant-input {
//   width: 283px;
// }
/deep/ .ant-modal-body {
  text-align: center;
}
.name_label {
  margin-left: 50px;
}
</style>